package com.dp.appi.controller;

import com.dp.appi.entity.UserEntity;
import com.dp.appi.exception.CommonException;
import com.dp.appi.exception.SendSMSException;
import com.dp.appi.service.PhotoService;
import com.dp.appi.service.SysConfigService;
import com.dp.appi.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.*;
import java.util.concurrent.*;

/**
 * Created by chenghao on 2015/9/30.
 */
@Controller
@RequestMapping(value = "/systemControl")
public class SysConfigControl {

    private static Logger log = LoggerFactory.getLogger(ConsumerControl.class);

    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private PhotoService photoService;
    /**
     * 获取APP基本配置
     *
     * @param modelMap
     */
    @RequestMapping(value = "/baseConfig")
    public void baseConfig(ModelMap modelMap) {
        try {
            //获取APP基本配置
            List<Map<String, Object>> lists1 = sysConfigService.queryBaseConfig();
            modelMap.addAttribute("baseConfig", lists1);
        } catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }

    @Value("${file_path}")
    private String file_path;


    /**
     * 异步上传单文件
     *
     * @param modelMap
     * @param request
     * @param file
     */
    @RequestMapping(value = "/upload", method = {RequestMethod.POST})
    public void images(ModelMap modelMap, HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        String type = request.getParameter("type");//上传的文件类型

        String _path = "";
        if (Constant.HEADER_TYPE.equals(type)) {
            _path += "header/";
        } else if (Constant.PROJECT_TYPE.equals(type)) {
            _path += "project/";
        } else if (Constant.RECON_FIRST_TYPE.equals(type)) {
            _path += "recon_first/";
        } else if (Constant.RECON_SECOND_TYPE.equals(type)) {
            _path += "recon_second/";
        } else if (Constant.RECON_THIRD_TYPE.equals(type)) {
            _path += "recon_third/";
        } else if (Constant.PROJECT_RADIO.equals(type)) {
            _path += "projectRadio/";
        } else {
            _path += "pic/";
        }
        _path = _path + DateUtil.getNowDateStr() + "/";
        try {
            File f = new File(file_path + _path);
            if (!f.exists()) {
                f.mkdirs();
            }

            String filename = file.getOriginalFilename();

            String[] _files = filename.split("\\.");
            String suffix = _files[1];
            _path += System.currentTimeMillis() + "." + suffix;

            String file_path1 = _path;
            String file_path2 = _path.replace(".amr", ".mp3");

            String path = file_path + _path;
            File targetFile = new File(path);

            file.transferTo(targetFile);

            //将amr格式文件转成MP3格式文件存储
            if (Constant.PROJECT_RADIO.equals(type))
                if (suffix.equals("amr")) {
                    try {
                        Amr_mp3_format.changeToMp3(file_path, file_path1, file_path2);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }


            modelMap.addAttribute("path", "upload/" + _path);
        } catch (IOException e) {
            e.printStackTrace();
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }

    /**
     * 异步上传单文件
     *
     * @param modelMap
     * @param request
     * @param file
     */
    @RequestMapping(value = "/uploadCut", method = {RequestMethod.POST})
    public void uploadCut(ModelMap modelMap, HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        String type = request.getParameter("type");//上传的文件类型

        String _path = "";
        if (Constant.HEADER_TYPE.equals(type)) {
            _path += "header/";
        } else if (Constant.PROJECT_TYPE.equals(type)) {
            _path += "project/";
        } else if (Constant.RECON_FIRST_TYPE.equals(type)) {
            _path += "recon_first/";
        } else if (Constant.RECON_SECOND_TYPE.equals(type)) {
            _path += "recon_second/";
        } else if (Constant.RECON_THIRD_TYPE.equals(type)) {
            _path += "recon_third/";
        } else if (Constant.PROJECT_RADIO.equals(type)) {
            _path += "projectRadio/";
        } else {
            _path += "pic/";
        }
        _path = _path + DateUtil.getNowDateStr() + "/";
        try {
            File f = new File(file_path + _path);
            if (!f.exists()) {
                f.mkdirs();
            }

            String filename = file.getOriginalFilename();

            String[] _files = filename.split("\\.");
            String suffix = _files[1];
            Long millis = System.currentTimeMillis();
            String _path1 = _path + millis + "." + suffix;

            String path = file_path + _path1;
            File targetFile = new File(path);

            file.transferTo(targetFile);
            modelMap.addAttribute("path", "upload/" + _path1);
            //生成切图
            ImageUtils.cut4(path, file_path + _path + millis + "_cut." + suffix);//测试OK
        } catch (IOException e) {
            e.printStackTrace();
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }

    /**
     * 异步上传多文件
     *
     * @param modelMap
     * @param request
     */
    @RequestMapping(value = "/uploadMore", method = {RequestMethod.POST})
    public void images(ModelMap modelMap, HttpServletRequest request) {
        String type = request.getParameter("type");//上传的文件类型
        String _path = "";
        if (Constant.HEADER_TYPE.equals(type)) {
            _path += "header/";
        } else if (Constant.PROJECT_TYPE.equals(type)) {
            _path += "project/";
        } else if (Constant.RECON_FIRST_TYPE.equals(type)) {
            _path += "recon_first/";
        } else if (Constant.RECON_SECOND_TYPE.equals(type)) {
            _path += "recon_second/";
        } else if (Constant.RECON_THIRD_TYPE.equals(type)) {
            _path += "recon_third/";
        } else if (Constant.PROJECT_RADIO.equals(type)) {
            _path += "projectRadio/";
        } else {
            _path += "pic/";
        }
        _path = _path + DateUtil.getNowDateStr() + "/";
        File f = new File(file_path + _path);
        if (!f.exists()) {
            f.mkdirs();
        }

        try {
            List<Future<String>> results = new ArrayList<>();
            ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
            Iterator<String> fileNames = ((MultipartHttpServletRequest) request).getFileNames();
            while (fileNames.hasNext()) {
                String fileName = fileNames.next();
                MultipartFile file = ((MultipartHttpServletRequest) request).getFile(fileName);
                Future<String> result = es.submit(new UploadFile(file, file_path, _path));
                results.add(result);
            }
            es.shutdown();

            List<String> l = new ArrayList<>();
            for (Future<String> s : results) {
                String str = s.get();
                if (!"".equals(str)) {
                    l.add(str);
                }
            }

            modelMap.addAttribute("path", l);
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }

    }

    static class UploadFile implements Callable<String> {
        private final String file_path;
        private final String _path;
        private final MultipartFile file;

        UploadFile(MultipartFile file, String file_path, String _path) {
            this.file = file;
            this.file_path = file_path;
            this._path = _path;
        }

        @Override
        public String call() throws Exception {
            String filename = file.getOriginalFilename();
            String[] _files = filename.split("\\.");
            String suffix = _files[1];
            String suffix_path = _path + System.currentTimeMillis() + "." + suffix.toLowerCase();
            String path = file_path + suffix_path;
            File targetFile = new File(path);

            try {
                file.transferTo(targetFile);
                return "upload/" + suffix_path;
            } catch (Exception e) {
                e.printStackTrace();
                log.error(ExceptionUtil.getExceptionAllinformation(e));
                return "";
            }
        }
    }

    /**
     * 获取平台配置的代码类型
     *
     * @param modelMap
     */
    @RequestMapping(value = "/sysType", method = RequestMethod.GET)
    public void sysType(ModelMap modelMap, @RequestParam("typegroupid") String typegroupid) {
        try {
            String[] typegroupids = typegroupid.split("\\|");
            if (typegroupids.length > 0) {
                for (int i = 0; i < typegroupids.length; i++) {
                    String temp = typegroupids[i];
                    List<Map<String, Object>> lists = sysConfigService.sysType(temp);
                    modelMap.addAttribute(temp, lists);
                }
            }
        } catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }

    /**
     * 获取系统文章内容
     *
     * @param param
     * @param modelMap
     */
    @RequestMapping(value = "/getSysArticleContent")
    public void getSysArticleContent(@RequestParam Map<String, String> param, ModelMap modelMap) {
        try {
            modelMap.addAttribute("articleContent", sysConfigService.getSysArticleContent(param));
        } catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }

    /**
     * 发送短信验证码
     *
     * @param param
     * @param modelMap
     */
    @RequestMapping(value = "/sendIdentCode", method = RequestMethod.GET)
    public void sendIdentCode(@RequestParam Map<String, String> param, ModelMap modelMap) {
        try {
            boolean boo = ValidCode.validCodeLimit(param.get("phone") + "_" + param.get("key"));
            if (!boo) {
                throw new CommonException("SMS005");
            }
            String code = ValidCode.getRandomCode();
            SendSMS sendSMS = new SendSMS();
            boolean bo = sendSMS.sendSMS(param.get("phone"), code, null, Integer.valueOf(param.get("templet")));
            ;
            if (bo == true) {
                ValidCode.setValidCode(param.get("phone") + "_" + param.get("key"), code);
                modelMap.addAllAttributes(SYS.SUCCESS.msgMap());
            } else {
                modelMap.addAllAttributes(SYS.SMS001.msgMap());
            }
        } catch (CommonException c) {
            modelMap.addAllAttributes(SYS.valueOf(c.getMessage()).msgMap());
        } catch (MalformedURLException e) {
            modelMap.addAllAttributes(SYS.L10006.msgMap());
        } catch (UnsupportedEncodingException e) {
            modelMap.addAllAttributes(SYS.L10006.msgMap());
        } catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
        }
    }

    /**
     * 首页轮播广告
     *
     * @param modelMap
     * @param request
     */
    @RequestMapping(value = "/carousel", method = {RequestMethod.GET})
    public void carousel(ModelMap modelMap, HttpServletRequest request) {
        try {
            modelMap.addAttribute("carousel", sysConfigService.getHomeAdvert("appHomeAd"));
        } catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }

    /**
     * 离线地图配置
     *
     * @param modelMap
     * @param request
     */
    @RequestMapping(value = "/baseConfig", method = {RequestMethod.GET})
    public void offlineMap(ModelMap modelMap, HttpServletRequest request) {
        try {
            modelMap.addAttribute("offlineMap", sysConfigService.offlineMap());
        } catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }

    /**
     * 获取系统消息列表
     *
     * @param modelMap
     * @param param
     */
    @RequestMapping(value = "/sysMessList", method = {RequestMethod.GET})
    public void userByTypeList(ModelMap modelMap, @RequestParam Map<String, String> param) {
        try {
            String openIdent = param.get("openIdent");
            int s = Integer.parseInt(param.get("s"));
            int n = Integer.parseInt(param.get("n"));
            Map<String, Object> user = sysConfigService.getUserByOpenIdent(openIdent);
            modelMap.addAttribute("sysMessList", sysConfigService.sysMessList(String.valueOf(user.get("id")), s, n));
        } catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }

    /**
     * 获取系统当前最新版本
     *
     * @param modelMap
     * @param request
     */
    @RequestMapping(value = "/sysVersion", method = {RequestMethod.GET})
    public void getSysVersion(ModelMap modelMap, HttpServletRequest request, @RequestParam Map<String, String> param) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        int soft_type = Integer.parseInt(param.get("soft_type"));
        resultMap.put("sysVersion", sysConfigService.getSysVersion(soft_type));
        modelMap.addAllAttributes(resultMap);
    }

    /**
     * 获取登录人单位照片类型配置
     *
     * @param modelMap
     */
    @RequestMapping(value = "/sysPhotoType", method = RequestMethod.GET)
    public void sysPhotoType(ModelMap modelMap, @RequestParam Map<String, String> param) {
        try {
            String openIdent = param.get("openIdent");
            Map<String, Object> user = sysConfigService.getUserByOpenIdent(openIdent);
           String  orgid =  user.get("org_id").toString();
            modelMap.addAttribute("photoList", photoService.getPhotoTypeByOrgId(orgid));

        } catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }

}
